package com.service.scheduling.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.service.dao.mapper.TradingSpotTradesMapper;
import com.service.dao.model.TradingSpotPairs;
import com.service.dao.model.TradingSpotTrades;
import com.service.scheduling.dto.SpotTradePriceVo;
import com.service.scheduling.service.TradingSpotPairsService;
import com.service.scheduling.service.TradingSpotTradesService;
import com.service.scheduling.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Service("tradingSpotTradesService")
public class TradingSpotTradesServiceImpl extends ServiceImpl<TradingSpotTradesMapper, TradingSpotTrades> implements TradingSpotTradesService {

    @Autowired
    private TradingSpotPairsService spotPairsService;

    @Override
    public Map<String, BigDecimal> getActualTimePrice() {
        Map<String, BigDecimal> result = Maps.newHashMap();
        List<TradingSpotPairs> pairsReps = spotPairsService.listPairs();
        pairsReps.parallelStream().forEach(item -> {
            TradingSpotTrades trade = getLastTrade(item.getSymbol());
            if (ObjectUtils.isEmpty(trade)) {
                return;
            }
            result.put(item.getCoinsName(), trade.getOrderPrice());
        });
        return result;
    }

    public TradingSpotTrades getLastTrade(String symbol) {
        return getOne(new QueryWrapper<TradingSpotTrades>().lambda()
                .eq(TradingSpotTrades::getSymbol, symbol).orderByDesc(TradingSpotTrades::getId).last("limit 1"));
    }

    @Override
    public SpotTradePriceVo getTradePrice(String coinName, Date someday) {
       TradingSpotPairs spotPairs = spotPairsService.getSpotPair(coinName);
        if(ObjectUtils.isEmpty(spotPairs)){
            return null;
        }

        Date startTime = DateUtil.getDayOfStart(someday);
        Date endTime = DateUtil.getDayOfEnd(someday);

        return SpotTradePriceVo.builder()
                .coinName(coinName)
                .maxPrice(baseMapper.getMaxPrice(spotPairs.getSymbol(), startTime, endTime))
                .minPrice(baseMapper.getMinPrice(spotPairs.getSymbol(), startTime, endTime))
                .build();
    }
}
